package mx.com.zl0.scheduler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import mx.com.zl0.scheduler.tasks.SchedulerTask;

public class SchedulerExecutor {

	private final Map<String, Scheduler> schedulers;

	public SchedulerExecutor(SchedulerTask... schedulerTasks) {
		schedulers = new HashMap<String, Scheduler>(schedulerTasks.length);
		for(SchedulerTask schedulerTask : schedulerTasks) {
			final Scheduler scheduler = new Scheduler(schedulerTask);
			schedulers.put(schedulerTask.getId(), scheduler);
		}
	}

	public void execute(String... schedulerTasks) {
		for (String schedulerTask : schedulerTasks) {
			if (schedulers.containsKey(schedulerTask) && !schedulers.get(schedulerTask).isRunning()) {
				schedulers.put(schedulerTask, new Scheduler(schedulers.get(schedulerTask).getSchedulerTask().execute(), true));
			}
		}
	}

	public void stop(String... schedulerTasks) {
		for (String schedulerTask : schedulerTasks) {
			if (schedulers.containsKey(schedulerTask) && schedulers.get(schedulerTask).isRunning()) {
				schedulers.get(schedulerTask).cancel();
			}
		}
	}

	public ArrayList<SchedulerTask> getTasks() {
		final ArrayList<SchedulerTask> schedulerTasks = new ArrayList<SchedulerTask>(schedulers.size());
		for(Scheduler scheduler : schedulers.values()) {
			schedulerTasks.add(scheduler.getSchedulerTask());
		}
		return schedulerTasks;
	}
}